package com.xuecheng.mybatis.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.xuecheng.commons.utils.AuthInfoHolder;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MyBatisPlusConfig {


   // 不需要多租户的表
   private static String[] tables = new String[]{"tb_dictionary", "tb_category",
           "undo_log", "tb_application", "tb_company", "tb_resource", "tb_role_resource", "tb_user_role"};

   //注册mybatis的插件
   @Bean
   public MybatisPlusInterceptor mybatisPlusInterceptor() {
      MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
      //多租户插件
      interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
         //多租户id
         @Override
         public Expression getTenantId() {
            //通过线程获取登录的企业id
            Long companyId = AuthInfoHolder.getCompanyId();
            //判断是否为企业用户
            if (companyId==null){
               return null;
            }
            return new LongValue(companyId);
         }
         //多租户字段
         @Override
         public String getTenantIdColumn() {
            return "company_id";
         }
         //不需要多租户隔离
         @Override
         public boolean ignoreTable(String tableName) {
            //非企业用户忽略
            if (getTenantId()==null){
               return true;
            }
            //指定表忽略
            if (ArrayUtil.containsIgnoreCase(tables,tableName)){
               return true;
            }
            return false;
         }
      }));
      //分页的插件
      interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
      return interceptor;
   }

}